<!DOCTYPE html>
<html lang="en">

<head>

<!-- AdThrive Head Tag Manual -->
<script data-no-optimize="1" data-cfasync="false">
(function(w, d) {
	w.adthrive = w.adthrive || {};
	w.adthrive.cmd = w.
	adthrive.cmd || [];
	w.adthrive.plugin = 'adthrive-ads-manual';
	w.adthrive.host = 'ads.adthrive.com';var s = d.createElement('script');
	s.async = true;
	s.referrerpolicy='no-referrer-when-downgrade';
	s.src = 'https://' + w.adthrive.host + '/sites/643436a4e6d20859e40a446b/ads.min.js?referrer=' + w.encodeURIComponent(w.location.href) + '&cb=' + (Math.floor(Math.random() * 100) + 1);
	var n = d.getElementsByTagName('script')[0];
	n.parentNode.insertBefore(s, n);
})(window, document);
</script>
<!-- End of AdThrive Head Tag -->





  <!-- Global site tag (gtag.js) - Google Analytics -->



  <script async src="https://www.googletagmanager.com/gtag/js?id=UA-79254642-6"></script>

  <script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());

    gtag('config', 'UA-79254642-6');
  </script>

  <meta charset="utf-8">
  <title>Basic violin plot in d3.js</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="Using d3.js to create a very basic violin plot. Simplest example with only the core code and explanations.">
  <meta name="keywords" content="Data, Dataviz, Datavisualization, Javascript, JS, d3.js, boxplot">
  <meta name="author" content="Yan Holtz">
  <link rel="icon" href="../img/logo/D3_single_small.png">

  <meta property="og:title" content="Basic violin plot in d3.js">
  <meta property="og:image" content="https://www.d3-graph-gallery.com/img/logo/D3_full_medium.png">
  <meta property="og:description" content="Using d3.js to create a very basic violin plot. Simplest example with only the core code and explanations.">

  <!-- Bootstrap core CSS -->
  <link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

  <!-- Custom fonts for this template -->
  <link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

  <!-- Custom styles for this template -->
  <link href="../css/agency.css" rel="stylesheet">

  <!-- PRISM -->
  <script src="../LIB/prism.js"></script>
  <link href="../LIB/prism.css" rel="stylesheet" />

  <!-- D3.JS v4 -->
  <script src="../js/d3.v4.js"></script>

  <!-- JQUERY -->
  <script src="../vendor/jquery/jquery.min.js"></script>

  <!-- HTML TO CANVAS -->
  <script src="../js/html2canvas.js"></script>

  <!-- Function to parse html and js code chunks made by Yan Holtz -->
  <script src="../js/myParser.js"></script>

</head>






<body id="page-top">


<!-- THIS ALLOWS TO INSERT THE MENU THAT IS STORED IN A MENU.HTML FILE-->
<nav class="navbar navbar-expand-lg fixed-top" id="mainNav"></nav>
<script>
$(function(){
  $("#mainNav").load("../html_chunk/menu.html");
});
</script>

<!-- THIS ALLOWS TO INSERT THE MODAL OF THE MENU THAT IS STORED IN A MENU_MODAL.HTML FILE-->
<div id="modal_menu_insertion"> </div>
<script>
$(function(){
  $("#modal_menu_insertion").load("../html_chunk/menu_modal.html");
});
</script>


<!-- Header -->
<header class="masthead">
  <div class="textlanding">
      <h1>Most basic violin plot in d3.js</h1>
      <hr class="short_hr">
      <br>
      <ul class="list-inline social-buttons">
        <li class="list-inline-item">
          <a href="https://twitter.com/R_Graph_Gallery">
            <i class="fa fa-twitter"></i>
          </a>
        </li>
        <li class="list-inline-item social-buttons">
          <a href="https://github.com/holtzy">
            <i class="fa fa-github" style="color: white"></i>
          </a>
        </li>
        <li class="list-inline-item social-buttons">
          <a href="https://www.linkedin.com/in/yan-holtz-2477534a/">
            <i class="fa fa-linkedin"></i>
          </a>
        </li>
        <li class="list-inline-item social-buttons">
          <a href="https://www.yan-holtz.com">
            <i class="fa fa-home"></i>
          </a>
        </li>
      </ul>
      <br><br>
      <p style="max-width: 700px; margin: auto">A <a href="../violin.html">violin plot</a> is an alternative to the more usual <a href="../boxplot.html">boxplot</a>, especially interesting with large dataset where boxplot could <a href="https://www.data-to-viz.com/caveat/boxplot.html">hide a part of the information</a>. Here is a simple implementation in d3.js using the <code>d3.histogram()</code> function, keeping only the core code to understand the fundamental concept.</p>
      <br>
      <a class="btn btn-secondary btn-md text-uppercase" href="../violin.html">Violin plot section</a>
      <button class="btn btn-secondary btn-md text-uppercase" onclick="myCodeDownload('chart_example_from_d3-graph-gallery.html', 'code-html-v4', 'code-js-v4')">Download code</button>
  </div>
</header>


















<section class="bg" style="padding-top: 20px; padding-bottom: 20px"><div class="container" >
  <div class="row">

<!-- ==================== GRAPH SECTION = WHERE THE GRAPH APPEARS ==================== -->

  <div class="col-lg-5 .align-middle">
    <div style="position: -webkit-sticky; position: sticky; top: 120px">
      <div class="bg-light" id="result" ></div>
      <br>
      <div>
        <h5>Steps:</h5>
        <ul>
          <br>
          <li>It is important to understand that this <a href="../violin.html">violin plot</a> is made using the <code>d3.histogram()</code> function, <u>not</u> using a kernel density estimate.</li>
          <br>
          <li>It takes the values of a group and split it in several <u>bins</u>. The number of value observed in each bin is represented, and a curve is used for <u>smoothing</u>.</li>
          <br>
          <li>The size of each bin is controlled by the <code>thresholds</code> argument of the <code>d3.histogram()</code> function. It is advised to <a href="https://www.data-to-viz.com/caveat/bin_size.html">try different bin size</a>.</li>
          <br>
          <li>Here, the highest number of item per bin is computed. This value will as wide as <u>100%</u> of the bandwidth. So you just have to play with the <code>padding</code> argument of the x axis to control space between violin.</li>
          <br>
          <li><u>Note</u>: With this method, a group with less values than another will have a smaller width.</li>
        </ul>
      </div>
    </div>
  </div>

<!-- ================================================================================= -->




<!-- ==================== CODE SECTION = WHERE THE CODE APPEARS ==================== -->
<div class="col-lg-7 text-center .align-middle">

<!-- ========= show html code ============== -->
<aside style="position: -webkit-sticky; position: sticky; top: 120px">&larr; Edit me! </aside>
<pre class="language-html d-none d3v4-chunk"><code id="code-html-v4" contenteditable="true"><xmp><!DOCTYPE html>
<meta charset="utf-8">

<!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>

<!-- Create a div where the graph will take place -->
<div id="my_dataviz"></div>

</xmp></code></pre>
<!-- ==================================== -->






<!-- ========= show JS code ==============  -->
<pre class="language-js d-none d3v4-chunk"><code id="code-js-v4" contenteditable="true"><xmp><script>

// set the dimensions and margins of the graph
var margin = {top: 10, right: 30, bottom: 30, left: 40},
    width = 460 - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom;

// append the svg object to the body of the page
var svg = d3.select("#my_dataviz")
  .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform",
          "translate(" + margin.left + "," + margin.top + ")");

// Read the data and compute summary statistics for each specie
d3.csv("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/iris.csv", function(data) {

  // Build and Show the Y scale
  var y = d3.scaleLinear()
    .domain([ 3.5,8 ])          // Note that here the Y scale is set manually
    .range([height, 0])
  svg.append("g").call( d3.axisLeft(y) )

  // Build and Show the X scale. It is a band scale like for a boxplot: each group has an dedicated RANGE on the axis. This range has a length of x.bandwidth
  var x = d3.scaleBand()
    .range([ 0, width ])
    .domain(["setosa", "versicolor", "virginica"])
    .padding(0.05)     // This is important: it is the space between 2 groups. 0 means no padding. 1 is the maximum.
  svg.append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x))

  // Features of the histogram
  var histogram = d3.histogram()
        .domain(y.domain())
        .thresholds(y.ticks(20))    // Important: how many bins approx are going to be made? It is the 'resolution' of the violin plot
        .value(d => d)

  // Compute the binning for each group of the dataset
  var sumstat = d3.nest()  // nest function allows to group the calculation per level of a factor
    .key(function(d) { return d.Species;})
    .rollup(function(d) {   // For each key..
      input = d.map(function(g) { return g.Sepal_Length;})    // Keep the variable called Sepal_Length
      bins = histogram(input)   // And compute the binning on it.
      return(bins)
    })
    .entries(data)

  // What is the biggest number of value in a bin? We need it cause this value will have a width of 100% of the bandwidth.
  var maxNum = 0
  for ( i in sumstat ){
    allBins = sumstat[i].value
    lengths = allBins.map(function(a){return a.length;})
    longuest = d3.max(lengths)
    if (longuest > maxNum) { maxNum = longuest }
  }

  // The maximum width of a violin must be x.bandwidth = the width dedicated to a group
  var xNum = d3.scaleLinear()
    .range([0, x.bandwidth()])
    .domain([-maxNum,maxNum])

  // Add the shape to this svg!
  svg
    .selectAll("myViolin")
    .data(sumstat)
    .enter()        // So now we are working group per group
    .append("g")
      .attr("transform", function(d){ return("translate(" + x(d.key) +" ,0)") } ) // Translation on the right to be at the group position
    .append("path")
        .datum(function(d){ return(d.value)})     // So now we are working bin per bin
        .style("stroke", "none")
        .style("fill","#69b3a2")
        .attr("d", d3.area()
            .x0(function(d){ return(xNum(-d.length)) } )
            .x1(function(d){ return(xNum(d.length)) } )
            .y(function(d){ return(y(d.x0)) } )
            .curve(d3.curveCatmullRom)    // This makes the line smoother to give the violin appearance. Try d3.curveStep to see the difference
        )
})

</script></xmp></code></pre>
<!-- ==================================== -->









</div>


  </div>
</div>
</section>
<br>


<!-- ============================ -->







<!-- ============================ ADDITIONAL NOTES =========================== -->

<section style="padding-top: 70px; padding-bottom: 70px">
  <div class="container">
    <center><h3>Variation</h3></center>
    <hr class="short_hr">
    <center><p style="max-width: 800px">It is important to understand that in the violin chart above the smoothing effect is due to a <u>curve interpolation</u> between bins. Here is the result <u>without</u> any interpolation (left) and using a <code>curveStep</code> interpolation (right). Just change the <code>.curve()</code> call in the code above to get these results.</p></center>
    <div class="row mx-auto">
      <div class="col-lg-6"><center><img src="../img/graph/violin_basicHist2.png"/></center></div>
      <div class="col-lg-6"><img src="../img/graph/violin_basicHist3.png"/></center></div>
    </div>
  </div>
</section>



<!-- ============================ RELATED BLOCKS ============================ -->

<section class="bg-light" style="padding-top: 70px; padding-bottom: 70px">
  <div class="container">
    <div class="row">
      <div class="col-lg-5 text-center align-self-center">
        <h3 class="text-uppercase">Related blocks  &rarr;</h3>
      </div>
      <div class="col-lg-5">
        <ul>
          <li><i>Histograms in d3.js - </i>by <a href="../histogram.html">the d3 graph gallery</a></li>
          <br>
          <li><i>Violin chart - </i>by <a href="https://bl.ocks.org/KingOfCramers/f019d2b34a3e8f8da307958b0d9e30cf">Harry</a></li>
        </ul>
      </div>
    </div>
  </div>
</section>

















<!-- ============================ CONTACT SECTION ============================ -->

  <!-- ANCHOR -->
  <a name="contactanchor"></a>


<section id="contact" class="bg" style="background-color: white"></section>

<!-- THIS ALLOWS TO INSERT THE CONTACT CHUNK THAT IS STORED IN A CONTACT.HTML FILE-->
<script>
$(function(){
  $("#contact").load("../html_chunk/contact.html");
});
</script>













<!-- ============================ FOOTER SECTION ============================ --><footer class="bg-light" id="myFooter"></footer>

<!-- THIS ALLOWS TO INSERT THE FOOTER THAT IS STORED IN A FOOTER.HTML FILE-->
<script>
$(function(){
  $("#myFooter").load("../html_chunk/footer.html");
});
</script>

<!-- ============================ -->




















<!-- ============================ JAVASCRIPT SECTION ============================ -->

<!-- Bootstrap core JavaScript -->
<script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

<!-- Custom scripts for this template -->
<script src="../js/agency.min.js"></script>

<!-- Activate the bootstrap tooltip, must be after jQuery load -->
<script>
  $(function () {
      $('[data-toggle="tooltip"]').tooltip()
  })
</script>



<script>
showCodeVersion('v4')
</script>







</body>

</html>
